﻿using System.Text;

namespace _66_C_读写dat二进制文件
{
    internal class Program
    {
        static string rootPath = @"test.dat";
        static void Main(string[] args)
        {

            Writebat();
            Readbat();
            Console.ReadKey();
        }

        public static void Writebat()
        {
            string filePath = "data.dat";

            // 写入二进制文件
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter writer = new BinaryWriter(fs))
            {
                //// 写入整数
                //writer.Write(42);
                //// 写入浮点数
                //writer.Write(3.44f);
                //// 写入浮点数
                //writer.Write(3.14f);
                //// 写入字符串
                //writer.Write("Hello, World!");

                int num = 89;
                byte[] bytes = BitConverter.GetBytes(num);
                //Encoding.UTF8.GetBytes();
                writer.Write(bytes, 0, bytes.Length);
            }

            Console.WriteLine("数据已写入到二进制文件: " + filePath);
        }

        public static void Readbat()
        {
            string filePath = "data.dat";

            // 读取二进制文件
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (BinaryReader reader = new BinaryReader(fs))
            {
                byte[] bytes = new byte[reader.BaseStream.Length];
                bytes= reader.ReadBytes(bytes.Length);
                int num = BitConverter.ToInt32(bytes);
                //// 读取整数
                //int intValue = reader.ReadInt32();
                //// 读取浮点数
                //float floatValue = reader.ReadSingle();
                //// 读取浮点数
                //float floatValue1 = reader.ReadSingle();
                //// 读取字符串
                //string stringValue = reader.ReadString();

                //Console.WriteLine("读取的数据:");
                //Console.WriteLine("整数: " + intValue);
                //Console.WriteLine("浮点数: " + floatValue);
                //Console.WriteLine("浮点数: " + floatValue1);
                //Console.WriteLine("字符串: " + stringValue);
                Console.WriteLine(num);
            }
        }
    }
}
